package org.mozhu.mboot.core.util;

import org.mozhu.mboot.core.ApplicationContextWrapper;
import org.mozhu.mboot.core.web.RequestContextHolder;
import org.springframework.beans.BeansException;
import org.springframework.context.MessageSource;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
import java.util.Optional;

public class MessageUtils {

    private static MessageSource messageSource;

    private static Optional<LocaleResolver> localeResolver;

    private static Locale resolveLocale(HttpServletRequest request) {
        if (request == null) {
            return Locale.getDefault();
        }
        if (localeResolver == null) {
            try {
                localeResolver = Optional.of(ApplicationContextWrapper.getContext().getBean(LocaleResolver.class));
            } catch (BeansException e) {
                localeResolver = Optional.empty();
            }
        }
        return localeResolver.isPresent() ? localeResolver.get().resolveLocale(request) : Locale.getDefault();
    }

    /**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     *
     * @param code 消息键
     * @param args 参数
     * @return
     */
    public static String message(String code, Object... args) {
        return message(code, args, resolveLocale(RequestContextHolder.getRequest()));
    }

    /**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     *
     * @param code 消息键
     * @param args 参数
     * @return
     */
    public static String message(String code, Object[] args, Locale locale) {
        if (messageSource == null) {
            messageSource = ApplicationContextWrapper.getContext().getBean(MessageSource.class);
        }
        try {
            return messageSource.getMessage(code, args, locale);
        } catch (Exception e) {

        }
        return null;
    }

}
